package com.yupi.yupicturebackend.controller;


import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.model.constant.UserConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Api( tags = "文件测试接口")
public class FileController {


    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    @Resource
    private CosManager cosManager;
    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "上传文件(仅管理员)")
    public BaseResponse<String> upload(@RequestParam("file") MultipartFile multipartFilefile) {
        //文件目录
        String fileName = multipartFilefile.getOriginalFilename();
        String filepath = String.format("/test/%s", fileName);
        File file = null;
        try {
            // 创建临时文件
            file  = File.createTempFile(filepath, null);
            multipartFilefile.transferTo(file);
            // 上传文件
            cosManager.putObject(filepath,file);
            // 返回结果
            return ResultUtils.success(filepath);
        } catch (Exception e) {
            log.info("file upload error ,filepath =" +filepath,e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath =" + filepath);
                }
            }
        }

        
    }

    @ApiOperation(value = "下载图片(仅管理员)")
    @GetMapping("/test/download")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public void download( String filepath, HttpServletResponse response) throws IOException {
        COSObjectInputStream objectContent = null;
        try {
            // 写入响应
            COSObject cosObject = cosManager.getObject(filepath);
            objectContent = cosObject.getObjectContent();
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment  ; filename ="  +  filepath);
            response.getOutputStream().write(IOUtils.toByteArray(objectContent));
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.info("file download error ,filepath =" +filepath,e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            // 关闭流
            if (objectContent != null){
                objectContent.close();
            }
        }
    }
}
